package com.anan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author anan
 * @date 2023/03/15/10:43
 **/
public class SqlSessionUtils {

    /**
     * 获取sqlSession对象
     */
    public static SqlSession getSqlSessionFactory(){
        try{
            //1. 加载核心配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml.bak");
            //2. 获取SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //3. 获取SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
            //4. 获取sqlSessio,即操作数据库的会话,并设置自动提交事务
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            return sqlSession;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实例化接口
     */
    public static <T> T getMapperFromSqlSession(Class<T> clazz){
        try{
            if(clazz != null) return getSqlSessionFactory().getMapper(clazz);
            else return null;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
